package com.hmdp.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private CacheClient cacheClient;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Shop queryShopById(Long id) {
        Shop shop = cacheClient.queryWithLogicalExpire(id, Shop.class, RedisConstants.LOCK_SHOP_KEY + id
                    , RedisConstants.CACHE_SHOP_KEY + id, this::getById, 30L, TimeUnit.MINUTES);
        if (shop == null) {
            throw new RuntimeException("店铺不存在");
        }
        return shop;
    }

    @Override
    public void updateShop(Shop shop) {
        boolean isSuccess = cacheClient.updateDBWithNoLock(shop, this::updateById
                , RedisConstants.CACHE_SHOP_KEY + shop.getId());
        if (!isSuccess) {
            throw new RuntimeException("更新店铺失败");
        }
    }

    @Override
    public void loadShopGeo2Redis() {
        // 1. 查出所有的店铺
        // 2. 根据shopType进行分组
        Map<Long, List<Shop>> shopTypeMap = list()
                .stream().collect(Collectors.groupingBy(Shop::getTypeId));
        // 3. 相同的shopType加入同一个geo里面，value为shopId，score值为x 和 y
        for (Long shopType : shopTypeMap.keySet()) {
            // 同一个type的shop
            List<Shop> shopList = shopTypeMap.get(shopType);
            // 同一个type的geoKey
            String key = RedisConstants.SHOP_GEO_KEY + shopType;
            // 批量添加
            List<RedisGeoCommands.GeoLocation<String>> geoLocationList = new ArrayList<>(shopList.size());
            for (Shop shop : shopList) {
                geoLocationList.add(new RedisGeoCommands.GeoLocation<>(
                        shop.getId().toString(),
                        new Point(shop.getX(), shop.getY()))
                );
            }
            stringRedisTemplate.opsForGeo().add(key, geoLocationList);
        }
    }

    @Override
    public List<Shop> queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        // 1. 判断是否是按照geo来查
        if (x == null || y == null) {
            // 2. 不是则返回普通的分页
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
           return page.getRecords();
        }

        // 3. 去redis中查出对应type的geo全部数据
        // geoKey
        String key = RedisConstants.SHOP_GEO_KEY + typeId;
        // 范围半价
        final double radius = 5000d;
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().search(
                key,
                GeoReference.fromCoordinate(x, y),
                new Distance(radius),
                RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
        );
        if (results == null) {
            // 范围内没有店铺
            return Collections.emptyList();
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> content = results.getContent();
        if (content.size() <= from) {
            // 没有下一页
            Collections.emptyList();
        }
        // 4. 手动分页
        List<Shop> shopList = content.stream().skip(from).map(geoLocationGeoResult -> {
            Long shopId = Long.valueOf(geoLocationGeoResult.getContent().getName());
            Distance distance = geoLocationGeoResult.getDistance();
            // 5. 去缓存中根据id去查出shop
            Shop shop = cacheClient.queryWithLogicalExpire(shopId, Shop.class, RedisConstants.LOCK_SHOP_KEY + shopId
                    , RedisConstants.CACHE_SHOP_KEY + shopId, this::getById, 30L, TimeUnit.MINUTES);
            shop.setDistance(distance.getValue());
            return shop;
        }).collect(Collectors.toList());
        // 6. 返回
        return shopList;
    }
}
